<script setup>
import _ from 'lodash';
import { useCommonStore } from '@jzl/stores';
import { onMounted, ref, watch } from 'vue';
import { api } from '@jzl/api';
import { DFT_FILL_ICONS, DFT_ICONS } from '@jzl/icons';

const DEFAULT_FORM = {
  icon: { icon: DFT_FILL_ICONS.dir, image: '', color: '#FCCB4A' },
  type: 1,
  ttys: [ 1, 2, 3 ],

  group_code: '',
  group_name: '',
  group_desc: ''
};

const emit = defineEmits(['success', 'cancel']);
const props = defineProps({
  actionType: {
    type: String,
    default: 'view'
  }, // action
  currentData: Object,
  tty: null,
  appId: null
});

const loading = ref(false);
const form = ref(_.cloneDeep(DEFAULT_FORM));

onMounted(() => {
  init();
});

watch(
  () => [props.actionType, props.currentData],
  () => {
    init();
  },
  { deep: true }
);

const init = () => {
  let iForm = null;
  if (props.actionType === 'createGroup' || props.actionType === 'createAppGroup') {
    let ttys = [];
    if (props.tty) {
      ttys = _.filter(
        _.map(`${props.tty || ''}`.split(''), (it) => it && Number(it)),
        (it) => it
      );
    } else {
      ttys = [1, 2, 3];
    }
    iForm = _.defaults(
      {
        project_id: useCommonStore().project?.project_id,
        parent_id: _.get(props.currentData, 'group_id', props.appId) || props.appId || -1,
        group_name: '',
        group_code: $utils.getNanoid(),
        group_desc: '',
        type: props.actionType === 'createAppGroup' ? 3 : 1,
        ttys: ttys,
        tty: props.tty
      },
      DEFAULT_FORM
    );
  } else {
    iForm = _.cloneDeep(props.currentData);

    if (!iForm.icon) {
      iForm.icon = { icon: '', color: '', image: '' };
    } else if (_.isString(iForm.icon)) {
      iForm.icon = { icon: iForm.icon, color: '', image: '' };
    }

    if(!iForm.icon.icon && iForm.icon.iconfont) {
      iForm.icon.icon = iForm.icon.iconfont;
    }

    if(iForm.type === 3) {  // 应用分组默认 123
      iForm.tty = '123';
    }
    if (/*this.ttyCustomReal && */ iForm.tty) {
      iForm.ttys = _.filter(
        _.map(`${iForm.tty}`.split(''), (it) => it && Number(it)),
        (it) => it
      );
    } else {
      iForm.ttys = [];
    }
  }

  form.value = iForm;
};

const handleSubmitCreateGroup = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'group_id');
  let ret = null;

  if (!data.group_code) {
    data.group_code = $utils.getNanoid();
  }

  if (/*this.ttyCustomReal && */ data.ttys) {
    data.tty = _.join(_.sortBy(data.ttys), '');
  }

  if (id) {
    ret = await api.group.updateGroup(id, data);
  } else {
    ret = await api.group.createGroup(data);
  }

  let tid =
    _.get(form.value, 'tid') ||
    `g_${_.get(ret, 'group_id')}` ||
    `g_${_.get(ret, 'content_group_id')}`;

  loading.value = false;
  $jui.toast('操作成功！');
  emit('success', tid);
  // this.refreshCurrentNode(tid);
};

const handleCancelEdit = () => {
  // props.actionType = 'view';
  emit('cancel');
};
</script>

<template>
  <el-form ref="formRef" label-width="100px">
    <el-form-item label="分组名称">
      <el-input
        v-model="form.group_name"
        placeholder="名称，如：产品分组"
        :disabled="actionType === 'view'"
      ></el-input>
    </el-form-item>
    <el-form-item label="菜单图标">
      <div class="icons" style="display: flex; align-items: center">
        <IconPicker
          v-model="form.icon.icon"
          size="mini"
          :is-view="actionType === 'view'"
          class="mr-2"
        />
        <el-color-picker
          v-model="form.icon.color"
          size="mini"
          :disabled="actionType === 'view'"
        />
        <!--<file-picker v-model="form.icon.image" theme="mini" :is-view="actionType == 'view'"></file-picker>-->
      </div>
    </el-form-item>
    <el-form-item
      label="适用终端"
      v-if="form.type != 3"
      ><!-- v-if="ttyCustomReal" -->
      <el-checkbox-group v-model="form.ttys" size="mini">
        <el-checkbox-button
          :label="1"
          :disabled="actionType === 'view'"
          v-tippy="{ arrow: true }"
          content="管理端"
        >
          <JIcon
            :icon="DFT_ICONS.mgr"
            class="fa fa-laptop"
            style="font-size: 12px; margin-right: 5px"
          /> MGR
        </el-checkbox-button>
        <el-checkbox-button
          :label="2"
          :disabled="actionType === 'view'"
          v-tippy="{ arrow: true }"
          content="手机端"
        >
          <JIcon
            :icon="DFT_ICONS.phone"
            class="fa fa-mobile-alt"
            style="font-size: 12px; margin-right: 5px"
          /> H5
        </el-checkbox-button>
        <el-checkbox-button
          :label="3"
          :disabled="actionType === 'view'"
          v-tippy="{ arrow: true }"
          content="PC端"
        >
          <JIcon
            :icon="DFT_ICONS.pc"
            class="fa fa-window-maximize1"
            style="font-size: 12px; margin-right: 5px"
          /> Web
        </el-checkbox-button>
      </el-checkbox-group>
    </el-form-item>
    <!--<el-form-item label="编码">
        <el-input v-model="form.group_code" placeholder="编码，如：PRODUCT_CAT"
                  :disabled="actionType == 'view'"></el-input>
    </el-form-item>-->
    <el-form-item label="分组描述">
      <el-input
        type="textarea"
        :rows="2"
        v-model="form.group_desc"
        :disabled="actionType === 'view'"
      ></el-input>
    </el-form-item>
    <el-form-item label="" v-if="actionType !== 'view'">
      <el-button size="default" type="primary" @click="handleSubmitCreateGroup()"> 提交 </el-button>
      <el-button size="default" @click="handleCancelEdit()"> 取消 </el-button>
    </el-form-item>
  </el-form>
</template>
